/**
 * 创建数据库
 */
function prepareDb(version, callback) {
    if (!window.openDatabase) {
        alert("浏览器不支持！");
        return;
    }
    var db = openDatabase('roster', '', 'Offline roster users storage', 5 * 1024 * 1024);
    if (db.version !== version) {
        reloadDb(db, version, callback);
    } else {
        callback();
    }
    return db;
}

/**
 * 刷新数据库数据
 */
function reloadDb(db, version,callback) {
    $.get("/users.json", function(data) {
        db.changeVersion(db.version, version, function(t) {
            t.executeSql('DROP TABLE IF EXISTS users');
            t.executeSql('CREATE TABLE users (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,cnname VARCHAR(50),workno INTEGER,email VARCHAR(50),phone VARCHAR(10),dept VARCHAR(50),py VARCHAR(10),duty VARCHAR(50))');
            $(data).each(function(i, u) {
                t.executeSql('INSERT INTO users(cnname,workno,email,phone,dept,py,duty) VALUES(?,?,?,?,?,?,?)',
                        [u.cnname, u.workno, u.email, u.phone, u.dept, u.py, u.duty]);
            });
            alert("数据已更新！");
            callback();
        }, function(e) {
            alert("浏览器错误" + e);
            console.log(e);
        }, $.noop);
    });
}

/**
 * 搜索数据库
 */
function searchDb(db, key, callback) {
    var sql = 'SELECT * FROM users WHERE ';
    var seg;
    if (/^\d+$/.test(key)) {
        sql += 'phone LIKE ? OR workno = ?';
        seg = [key + "%", key];
    } else if (/^[a-zA-Z]+$/.test(key)) {
        sql += 'py LIKE ? OR email LIKE ?';
        seg = [key + "%", key + "%"];
    } else if (/[\u4e00-\u9fa5]+/.test(key)) {
        sql += 'cnname LIKE ? OR dept LIKE ?';
        seg = [key + "%", "%" + key + "%"];
    }
    db.readTransaction(function(t) {
        t.executeSql(sql, seg, function(t, data) {
            callback(data);
        });
    }, function(e) {
        alert("本地数据库错误！" + e)
        console.log(e);
    });
}